package io.github.lee.jel.ui.add

import android.app.Application
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.core.vm.BaseViewModel
import io.github.lee.core.vm.err.ApplicationException
import io.github.lee.core.vm.err.ResultDataNullException
import io.github.lee.core.vm.err.ViewModelException
import io.github.lee.jel.R
import io.github.lee.jel.global.http.interceptors.resetHttp
import io.github.lee.repository.jel.repo.UserRepository
import javax.inject.Inject

@HiltViewModel
class AddServerVM @Inject constructor(
    application: Application,
    private val repo: UserRepository
) : BaseViewModel(application) {

    val nameObs = ObservableField("我的Jellyfin")
    val hostObs = ObservableField("https://jel.291700351.xyz")
    val usernameObs = ObservableField("291700351")
    val passwordObs = ObservableField("99233123")

    val loginSuccessLiveData = MutableLiveData(false)


    //===Desc:=============================================================

    fun submit() {
        val name = nameObs.get()
        if (name.isNullOrEmpty()) {
            toast(R.string.tip_input_name)
            return
        }
        val host = hostObs.get()
        if (host.isNullOrEmpty()) {
            toast(R.string.tip_input_address)
            return
        }
        val username = usernameObs.get()
        if (username.isNullOrEmpty()) {
            toast(R.string.tip_input_username)
            return
        }
        val password = passwordObs.get()
        if (password.isNullOrEmpty()) {
            toast(R.string.tip_input_password)
            return
        }
        // 提交
        showProgress(getString(R.string.txt_loading))
        launchResult(
            block = {
                resetHttp(host, username)
                repo.login(name, host, username, password)
            },
            error = {
                hideProgress()
                toast(it?.format(mContext) ?: ApplicationException(mContext).format(mContext))
            }
        ) {
            hideProgress()
            if (!it.isSuccess) {
                toast(ViewModelException(it.code, it.msg))
                return@launchResult
            }
            val data = it.data
            if (null == data) {
                toast(ResultDataNullException(mContext))
                return@launchResult
            }
            resetHttp(host, username, data.accessToken)
            loginSuccessLiveData.postValue(true)
        }


    }

}